package com.dys.hejiayuncommunity.web.controller.common;

import com.dys.hejiayuncommunity.common.constant.Constants;
import com.dys.hejiayuncommunity.common.utils.ChainedMap;
import com.dys.hejiayuncommunity.common.utils.UUIDUtils;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @Author: 疾风
 * @ClassName: CaptchaController
 * @Description: 验证码生成控制器
 * @CreateDate: 2024/12/18
 * @Version: v1.0.0
 */
@RestController
public class CaptchaController {

    /**
     * 当Redis当做数据库或者消息队列来操作时，我们一般使用RedisTemplate来操作
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/captchaImage")
    public ChainedMap getCode(HttpServletResponse response){
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);

        // 生成验证码,及验证码唯一标识
        String uuid = UUIDUtils.simpleUUID();
        String key = Constants.CAPTCHA_CODE_KEY+ uuid;
        String code = specCaptcha.text().toLowerCase();

        // 保存到Redis
        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(30));

        return ChainedMap.create().set("uuid",uuid).set("img",specCaptcha.toBase64());
    }
}
